<?php
namespace api\user\controller;
header("Content-type: text/html; charset=utf-8");
use api\user\model\UserOrderModel;
use api\common\controller\RestUserBaseController;
use api\user\model\ConfigModel;
use think\Db;
use think\Validate;
use fast\Http;
use fast\Alipay;

class OrderController extends RestUserBaseController
{
    protected $UserOrderModel;

    public function __construct()
    {
        parent::__construct();
        $this->UserOrderModel = new UserOrderModel();
    }

    /**
     * 交易订单列表
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function list()
    {
        $sell_max_num    = ConfigModel::getConfig('trade','sell_max_num');
        $recommend_price = ConfigModel::getConfig('trade','mq_to_mu');
        $service_fee     = ConfigModel::getConfig('trade','service_fee');
        $config = [];
        //卖单数量上限
        $config['sell_max_num']    = isset($sell_max_num['value']) ? $sell_max_num['value'] : 0;
        //推荐价
        $config['recommend_price'] = isset($recommend_price['value']) ? $recommend_price['value'] : 0;
        //手续费
        $service_fee             = isset($service_fee['value']) ? $service_fee['value'] : 0;
        $config['service_fee'] = $service_fee/100;

        $map['order_type'] =1;
        $map['order_status'] =2;
        $data = $this->UserOrderModel
        ->where($map)
        ->limit(200)
        ->order('sell_price desc')
        ->select();
        $this->success('请求成功', ['config'=>$config,'list' => $data]);
    }
    /**
     * 我的订单列表
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function index()
    {
        $param = $this->request->param();
        $map['where'] = [
            'user_id|buyer_id' => $this->userId
        ];

        if(isset($param['type'])){
            if(!empty($param['type'])){
                $map['where']['order_type'] = $param['type'];
            }
        }

        if (!empty($param['page'])) {
            $map['page'] = $param['page'];
        }

        if (isset($param['order_status'])&&($param['order_status'] !='')) {
            $map['where']['order_status'] = $param['order_status'];
        }
        $map['order'] = '-createtime';
        $data = $this->UserOrderModel
        ->getDatas($map);
        $this->success('请求成功', ['list' => $data]);
    }

    /**
     * 币币交易卖出
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function coinsellout()
    {
        $param         = $this->request->param();
        $verify_switch = getconfig('verify_switch');
        if($verify_switch>0){
          if(empty($this->user['verify_status'])){
            $this->error(['code' => 10052, 'msg' => '请先完成实名认证']);
            }  
        }
        $validate = new Validate([
            'coin_num'     =>'require|number|gt:0',
            'sell_price'   =>'require|number|gt:0',
            'pay_password' =>'require',
        ]);
        $validate->message([
            'coin_num.require'     =>'请输入卖出数量',
            'coin_num.number'      =>'请输入有效卖出数量',
            'coin_num.gt'          =>'请输入正确的卖出数量',
            'sell_price.require'   =>'请输入卖出价格',
            'sell_price.number'    =>'请输入有效卖出价格',
            'sell_price.gt'        =>'请输入正确的卖出价格',
            'pay_password.require' =>'请输入支付密码',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        
        if (empty($this->user['pay_password'])) {
            $this->error(['code' => 10051, 'msg' => '请先设置支付密码']);
        }
        if ($this->user['pay_password'] != getEncryptPassword($param['pay_password'], $this->user['pay_salt'])) {
            $this->error('支付密码错误');
        }
        //$param['coin_num'] = $param['coin_num'];
        if($param['coin_num']<1){
            $this->error('最低售卖数量1');
        }
        $sell_max_num    = ConfigModel::getConfig('trade','sell_max_num');
        $mq_to_mu = ConfigModel::getConfig('trade','mq_to_mu');
        $service_fee     = ConfigModel::getConfig('trade','service_fee');
        $mq_range = ConfigModel::getConfig('trade','mq_range');
        $sell_max_num    = isset($sell_max_num['value']) ? $sell_max_num['value'] : 10;
        $mq_to_mu_price = isset($mq_to_mu['value']) ? $mq_to_mu['value'] : 100;
        $mq_range_value = isset($mq_range['value']) ? $mq_range['value'] : 2.51;
        $service_fee     = isset($service_fee['value']) ? $service_fee['value'] : 5;
        $unit_price = $param['sell_price'];
        $max_sell_price = $mq_to_mu_price*$mq_range_value;
        $min_sell_price = $mq_to_mu_price*0.9;
        $mq_range_value_text = $mq_range_value*100;
        if ($unit_price > $max_sell_price) {
            $this->error('单价不能超过参考价'.$mq_range_value_text.'%');
        } 

        if ($unit_price < 1.9) {
            $this->error('单价不能低于1.9');
        } 
        
        //加锁
        $file = fopen("../lock/coinselloutlock.txt", "r");
        //进行排它型锁定,阻塞:后面的进程会一直等待前面的进程执行完毕
        if (flock($file, LOCK_EX)) {//加锁
            //卖单数量上限
            if (!empty($sell_max_num)) {
                 $user_order_count = Db::name('user_order')
                ->where(['user_id'=>$this->userId,'order_type'=>1])
                ->whereTime('createtime', 'd')
                ->lock(true)
                ->count();
                if (($user_order_count + 1)> $sell_max_num) {
                    $this->error('今日卖单数量已达上限');
                }
            }
            $service_fee_total = 0;
            if($service_fee>0){
                $service_fee_total = $param['coin_num']*$service_fee/100;
            }
            $needmq = $param['coin_num']+$service_fee_total;
            
            //我的卖单
            $user_order['order_no']     = cmf_get_order_sn();
            $user_order['user_id']      = $this->userId;
            $user_order['order_type']   = 1;//订单类型:1=币币交易,2=OTC通道买入,3=OTC通道卖出
            $user_order['order_status'] = 2;//订单状态:0=已撤销,1=已完成,2=售卖中
            $user_order['order_title']  = '币币交易';
            $user_order['transfer_fee'] = $service_fee_total;
            $user_order['coin_type']    = 2;//资产类型:1=MU,2=MQ
            $user_order['coin_num']     = $param['coin_num'];
            $user_order['sell_price']   = $unit_price*$param['coin_num'];
            $user_order['unit_price']   = $unit_price;
            $user_order['createtime']   = time();
            // 启动事务
            Db::startTrans();
            try {
                $user_info = Db::name('user')->where('id',$this->userId)->lock(true)->find();
                if($user_info['mq']<$needmq){
                    $this->error('可售MQ资产不足');
                }
                $order_id = Db::name('user_order')->insertGetId($user_order);
                Db::name('user')
                ->where('id', $this->userId)
                ->setDec('mq', $needmq);
                //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                $user_balance_log['user_id']    = $this->userId;
                $user_balance_log['amount']     = $needmq;
                $user_balance_log['before']     = $user_info['mq'];
                $user_balance_log['after']      = $user_info['mq'] - $needmq;
                $user_balance_log['remark']     = '币币交易卖出';
                $user_balance_log['type']       = 0;
                $user_balance_log['log_type']   = 3;
                $user_balance_log['source']     = 2;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);
                // 提交事务
                Db::commit();
                $this->success('发布成功',['order_id'=>$order_id]);
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('发布失败');
            }

            //释放锁
            flock($file, LOCK_UN);
        }
        fclose($file);

    }

    /**
     * 币币交易买入
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function coinsellin()
    {
        $param         = $this->request->param();
        $verify_switch = getconfig('verify_switch');
        if($verify_switch>0){
          if(empty($this->user['verify_status'])){
            $this->error(['code' => 10052, 'msg' => '请先完成实名认证']);
            }  
        }
        $validate = new Validate([
            'order_id'     =>'require|number|gt:0',
            'pay_password' =>'require',
        ]);
        $validate->message([
            'order_id.require'     =>'订单参数有误',
            'order_id.number'      =>'订单参数有误',
            'order_id.gt'          =>'订单参数有误',
            'pay_password.require' =>'请输入支付密码',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $find_order = Db::name('user_order')
        ->where(['id'=>$param['order_id'],'order_type'=>1,'order_status'=>2])
        ->lock(true)
        ->find();
        if (empty($find_order)) {
            $this->error('订单不存在');
        }

        if ($find_order['user_id'] ==$this->userId) {
            $this->error('你不能购买自己发布的订单');
        }

        if (empty($this->user['pay_password'])) {
            $this->error(['code' => 10051, 'msg' => '请先设置支付密码']);
        }
        if ($this->user['pay_password'] != getEncryptPassword($param['pay_password'], $this->user['pay_salt'])) {
            $this->error('支付密码错误');
        }
        
        //加锁
        $file = fopen("../lock/coinsellinlock.txt", "r");
        //进行排它型锁定,阻塞:后面的进程会一直等待前面的进程执行完毕
        if (flock($file, LOCK_EX)) {//加锁
            $needmu = $find_order['sell_price'];
            // 启动事务
            Db::startTrans();
            try {
                $user_info = Db::name('user')->where('id',$this->userId)->lock(true)->find();
                if($user_info['pay_mu']>=$needmu){
                    $buy_type = 1;
                    $wallet_type = 'pay_mu';
                }elseif($user_info['active_mu']>=$needmu){
                    $buy_type = 2;
                    $wallet_type = 'active_mu';
                }else{
                    $this->error('MU资产不足');
                }
                $update['order_status'] = 1;
                $update['buyer_id'] = $this->userId;
                $update['paytime']      = time();
                $update['buy_type']     = $buy_type;//购买消耗资产类型:1=充值MU,2=活动MU
                Db::name('user_order')
                ->where(['id'=>$param['order_id'],'order_type'=>1])
                ->update($update);
                //减掉买入者MU资产
                Db::name('user')
                ->where('id', $this->userId)
                ->setDec($wallet_type, $needmu);
                //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                $user_balance_log['user_id']    = $this->userId;
                $user_balance_log['amount']     = $needmu;
                $user_balance_log['before']     = $user_info[$wallet_type];
                $user_balance_log['after']      = $user_info[$wallet_type] - $needmu;
                $user_balance_log['remark']     = '币币交易买入';
                $user_balance_log['type']       = 0;
                $user_balance_log['log_type']   = $buy_type;
                $user_balance_log['source']     = 1;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);
                //增加买入者MQ资产
                Db::name('user')
                ->where('id', $this->userId)
                ->setInc('mq', $find_order['coin_num']);
                $user_balance_log['user_id']    = $this->userId;
                $user_balance_log['amount']     = $find_order['coin_num'];
                $user_balance_log['before']     = $user_info['mq'];
                $user_balance_log['after']      = $user_info['mq'] + $find_order['coin_num'];
                $user_balance_log['remark']     = '币币交易买入';
                $user_balance_log['type']       = 1;
                $user_balance_log['log_type']   = 3;
                $user_balance_log['source']     = 1;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);

                //增加卖出者资产
                Db::name('user')
                ->where('id', $find_order['user_id'])
                ->setInc($wallet_type, $needmu);
                $user_balance_log['user_id']    = $find_order['user_id'];
                $user_balance_log['amount']     = $needmu;
                $user_balance_log['before']     = $user_info[$wallet_type];
                $user_balance_log['after']      = $user_info[$wallet_type] + $needmu;
                $user_balance_log['remark']     = '币币交易卖出';
                $user_balance_log['type']       = 1;
                $user_balance_log['log_type']   = $buy_type;
                $user_balance_log['source']     = 2;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);
                // 提交事务
                Db::commit();
                $this->success('购买成功');
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('购买失败');
            }

            //释放锁
            flock($file, LOCK_UN);
        }
        fclose($file);

    }

    /**
     * 订单详情
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function detail(){
        $order_id = $this->request->get('order_id');
        if(!$order_id){
            $this->error('参数错误');
        }
        $detail = $this->UserOrderModel->where('id',$order_id)->find();
        $this->success('请求成功',['detail'=>$detail]);
    }

    /**
     * 币币订单撤销
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function revoke()
    {
       $order_id = $this->request->post('order_id');
        if(!$order_id){
            $this->error('参数错误');
        }
        //加锁
        $file = fopen("../lock/revokelock.txt", "r");
        //进行排它型锁定,阻塞:后面的进程会一直等待前面的进程执行完毕
        if (flock($file, LOCK_EX)) {//加锁
            // 启动事务
            Db::startTrans();
            try {
                $find_order = Db::name('user_order')
                ->where(['id'=>$order_id,'order_type'=>1,'order_status'=>2])
                ->lock(true)
                ->find();
                if (empty($find_order)) {
                    $this->error('订单不存在');
                }
                $needmq    = $find_order['coin_num']+$find_order['transfer_fee'];
                $user_info = Db::name('user')->where('id',$this->userId)->lock(true)->find();
                $update['order_status'] = 0;
                $update['revoketime']   = time();
                Db::name('user_order')
                ->where(['id'=>$order_id,'order_type'=>1])
                ->update($update);
                //返还卖出者资产
                Db::name('user')
                ->where('id', $find_order['user_id'])
                ->setInc('mq', $needmq);
                //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                $user_balance_log['user_id']    = $find_order['user_id'];
                $user_balance_log['amount']     = $needmq;
                $user_balance_log['before']     = $user_info['mq'];
                $user_balance_log['after']      = $user_info['mq'] + $needmq;
                $user_balance_log['remark']     = '撤销订单';
                $user_balance_log['type']       = 1;
                $user_balance_log['log_type']   = 3;
                $user_balance_log['source']     = 9;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);
                // 提交事务
                Db::commit();
                $this->success('撤销成功');
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('撤销失败');
            }

            //释放锁
            flock($file, LOCK_UN);
        }
        fclose($file);
    }

    /**
     * OTC卖出
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function otcsellout()
    {
        $param         = $this->request->param();
        $verify_switch = getconfig('verify_switch');
        if($verify_switch>0){
          if(empty($this->user['verify_status'])){
            $this->error(['code' => 10052, 'msg' => '请先完成实名认证']);
            }  
        }
        $user_miner_count = Db::name('user_miner')
        ->where(['user_id'=>$this->userId])
        ->where('miner_id','>',0)
        ->lock(true)
        ->count();
        //未购买就提示需要购买任意云矿机
        if($user_miner_count<1){
            $this->error('需要购买任意云矿机激活账户后才能卖出');
        }  

        $validate = new Validate([
            'coin_num'     =>'require|number|gt:0',
            'collection_type'   =>'require',
            'pay_password' =>'require',
        ]);
        $validate->message([
            'coin_num.require'     =>'请输入数量',
            'coin_num.number'      =>'请输入有效数量',
            'coin_num.gt'          =>'请输入正确的数量',
            'collection_type.require'   =>'请选择收款方式',
            // 'sell_price.number'    =>'请输入有效卖出价格',
            // 'sell_price.gt'        =>'请输入正确的卖出价格',
            'pay_password.require' =>'请输入支付密码',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        
        if (empty($this->user['pay_password'])) {
            $this->error(['code' => 10051, 'msg' => '请先设置支付密码']);
        }
        if ($this->user['pay_password'] != getEncryptPassword($param['pay_password'], $this->user['pay_salt'])) {
            $this->error('支付密码错误');
        }
        $param['coin_num'] = round($param['coin_num'],2);
        if($param['coin_num']<1.5){
            $this->error('最低数量1.5');
        }

        // $today_max_price = ConfigModel::getConfig('trade','today_max_price');
        // $today_min_price = ConfigModel::getConfig('trade','today_min_price');
        // $sell_max_num    = ConfigModel::getConfig('trade','sell_max_num');
        // $recommend_price = ConfigModel::getConfig('trade','recommend_price');
        // $service_fee     = ConfigModel::getConfig('trade','service_fee');
        // $today_max_price = isset($today_max_price['value']) ? $today_max_price['value'] : 0;
        // $today_min_price = isset($today_min_price['value']) ? $today_min_price['value'] : 0;
        // $sell_max_num    = isset($sell_max_num['value']) ? $sell_max_num['value'] : 0;
        // $recommend_price = isset($recommend_price['value']) ? $recommend_price['value'] : 0;
        // $service_fee     = isset($service_fee['value']) ? $service_fee['value'] : 0;
        
        // if($today_max_price){
        //    if ($param['sell_price'] > $today_max_price) {
        //         $this->error('卖出不能超过今日最高卖价');
        //     } 
        // }

        // if($today_min_price){
        //    if ($param['sell_price'] < $today_min_price) {
        //         $this->error('卖出不能低于今日最低卖价');
        //     } 
        // }
        
        //加锁
        $file = fopen("../lock/otcselloutlock.txt", "r");
        //进行排它型锁定,阻塞:后面的进程会一直等待前面的进程执行完毕
        if (flock($file, LOCK_EX)) {//加锁
            //卖单数量上限
            // if (!empty($sell_max_num)) {
            //      $user_order_count = Db::name('user_order')
            //     ->where(['user_id'=>$this->userId,'order_type'=>2])
            //     ->whereTime('createtime', 'd')
            //     ->lock(true)
            //     ->count();
            //     if (($user_order_count + 1)> $sell_max_num) {
            //         $this->error('今日卖单数量已达上限');
            //     }
            // }
            $service_fee_total = $param['coin_num']*0.02;
            
            $needmu = $param['coin_num'];
            $collection_type = $param['collection_type']>1?2:1;
            $collection_account = '';
            if($collection_type ==1){
                $config = wechat_config();
                $find = Db::name('third_party_user')
                ->where(['app_id'=>$config['appid'],'user_id'=>$this->userId])
                ->find();
                if(!$find){
                    $this->error("请阅读'微信提取流程'后进行绑定");
                }
            }else{
                $bankpay = Db::name('user')
                ->where(['id'=>$this->userId])
                ->value('bankpay');
                if(empty($bankpay)){
                    $this->error(['code' => 10053, 'msg' => '请先绑定银行卡']);
                }else{
                    $collection_account = $bankpay;
                }
            }
            //我的卖单
            $user_order['order_no']     = cmf_get_order_sn();
            $user_order['user_id']      = $this->userId;
            $user_order['order_type']   = 3;//订单类型:1=币币交易,2=OTC通道买入,3=OTC通道卖出
            $user_order['order_status'] = 3;//订单状态:0=已撤销,1=已完成,2=售卖中,3=待审核
            $user_order['order_title']  = 'OTC交易-卖出';
            $user_order['transfer_fee'] = $service_fee_total;
            $user_order['coin_type']    = 1;//资产类型:1=MU,2=MQ
            $user_order['collection_type']    = $collection_type;//收款账户:1=微信,2=银行卡
            $user_order['collection_account']    = $collection_account;
            $user_order['coin_num']     = $param['coin_num'];
            $user_order['sell_price']   = $param['coin_num']-$service_fee_total;
            $user_order['createtime']   = time();
            // 启动事务
            Db::startTrans();
            try {
                $user_info = Db::name('user')->where('id',$this->userId)->lock(true)->find();
                if($user_info['active_mu']<$needmu){
                    $this->error('可用MU资产不足');
                }
                $order_id = Db::name('user_order')->insertGetId($user_order);
                Db::name('user')
                ->where('id', $this->userId)
                ->setDec('active_mu', $needmu);
                //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                $user_balance_log['user_id']    = $this->userId;
                $user_balance_log['amount']     = $needmu;
                $user_balance_log['before']     = $user_info['active_mu'];
                $user_balance_log['after']      = $user_info['active_mu'] - $needmu;
                $user_balance_log['remark']     = 'OTC交易卖出';
                $user_balance_log['type']       = 0;
                $user_balance_log['log_type']   = 2;
                $user_balance_log['source']     = 4;
                $user_balance_log['createtime'] = time();
                Db::name('user_balance_log')->insert($user_balance_log);
                // 提交事务
                Db::commit();
                $this->success('提交成功,等待系统审核',['order_id'=>$order_id]);
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('发布失败');
            }

            //释放锁
            flock($file, LOCK_UN);
        }
        fclose($file);

    }

    /**
     * OTC交易买入
     * @author M
     * @data             2020-02-08
     * @return [type] [description]
     */
    public function otcsellin()
    {
        $this->error('通道维护');
        $param         = $this->request->param();
        $verify_switch = getconfig('verify_switch');
        if($verify_switch>0){
          if(empty($this->user['verify_status'])){
            $this->error(['code' => 10052, 'msg' => '请先完成实名认证']);
            }  
        }
        $validate = new Validate([
            'coin_num'     =>'require|number',
            'pay_type'     =>'require',
            //'pay_password' =>'require',
        ]);
        $validate->message([
            'coin_num.require'     =>'请输入购买数量',
            'coin_num.number'      =>'请输入有效购买数量',
            'pay_type.require'     =>'请选择支付方式',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        
        // if (empty($this->user['pay_password'])) {
        //     $this->error(['code' => 10051, 'msg' => '请先设置支付密码']);
        // }
        // if ($this->user['pay_password'] != getEncryptPassword($param['pay_password'], $this->user['pay_salt'])) {
        //     $this->error('支付密码错误');
        // }

        // $today_max_price = ConfigModel::getConfig('trade','today_max_price');
        // $today_min_price = ConfigModel::getConfig('trade','today_min_price');
        // $sell_max_num    = ConfigModel::getConfig('trade','sell_max_num');
        // $recommend_price = ConfigModel::getConfig('trade','recommend_price');
        // $service_fee     = ConfigModel::getConfig('trade','service_fee');
        // $today_max_price = isset($today_max_price['value']) ? $today_max_price['value'] : 0;
        // $today_min_price = isset($today_min_price['value']) ? $today_min_price['value'] : 0;
        // $sell_max_num    = isset($sell_max_num['value']) ? $sell_max_num['value'] : 0;
        // $recommend_price = isset($recommend_price['value']) ? $recommend_price['value'] : 0;
        // $service_fee     = isset($service_fee['value']) ? $service_fee['value'] : 0;
        
        // if($today_max_price){
        //    if ($param['sell_price'] > $today_max_price) {
        //         $this->error('卖出不能超过今日最高卖价');
        //     } 
        // }

        // if($today_min_price){
        //    if ($param['sell_price'] < $today_min_price) {
        //         $this->error('卖出不能低于今日最低卖价');
        //     } 
        // }
        
        //加锁
        $file = fopen("../lock/otcsellinlock.txt", "r");
        //进行排它型锁定,阻塞:后面的进程会一直等待前面的进程执行完毕
        if (flock($file, LOCK_EX)) {//加锁
            //卖单数量上限
            // if (!empty($sell_max_num)) {
            //      $user_order_count = Db::name('user_order')
            //     ->where(['user_id'=>$this->userId,'order_type'=>2])
            //     ->whereTime('createtime', 'd')
            //     ->lock(true)
            //     ->count();
            //     if (($user_order_count + 1)> $sell_max_num) {
            //         $this->error('今日卖单数量已达上限');
            //     }
            // }
            $service_fee_total = 0;
            // if($service_fee>0){
            //     $service_fee_total = $param['coin_num']*$service_fee/100;
            // }
            // $needmq = $param['coin_num']+$service_fee_total;
            
            //我的卖单
            $user_order['order_no']     = cmf_get_order_sn();
            $user_order['user_id']      = $this->userId;
            $user_order['order_type']   = 2;//订单类型:1=币币交易,2=OTC通道买入,3=OTC通道卖出
            $user_order['order_status'] = 4;//订单状态:0=已撤销,1=已完成,2=售卖中,3=待审核,4=待支付
            $user_order['order_title']  = 'OTC交易-买入';
            $user_order['transfer_fee'] = $service_fee_total;
            $user_order['coin_type']    = 1;//资产类型:1=MU,2=MQ
            $user_order['coin_num']     = $param['coin_num'];
            $user_order['pay_type']     = $param['pay_type'];
            $user_order['sell_price']   = $param['coin_num'];
            $user_order['createtime']   = time();
            // 启动事务
            Db::startTrans();
            try {
                $order_id = Db::name('user_order')->insertGetId($user_order);
                $url = url('index/user/pay',['id'=>$order_id],'',true);
                // 提交事务
                Db::commit();
                $this->success('提交成功',['url'=>$url]);
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                //$this->error($exception->getMessage());
                $this->error('提交失败');
            }

            //释放锁
            flock($file, LOCK_UN);
        }
        fclose($file);

    }

}
